from datetime import datetime, timedelta

from zope.interface import implements

from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from plone.app.portlets.portlets import base
from interfaces import IDiasFormar
from Acquisition import aq_inner,aq_parent

class Assignment(base.Assignment):
    implements(IDiasFormar)

    @property
    def title(self):
        return u"Dias para formar"
    
class Renderer(base.Renderer):
    implements(IDiasFormar)
    
    render = ViewPageTemplateFile('dias_formar.pt')
    
    def _get_member(self):
        context = aq_inner(self.context)
        member = context.portal_membership.getAuthenticatedMember()
        if member.getMemberId() == 'Anonymous':
            return None
        return member
        
    
    @property
    def available(self):
        member = self._get_member()
        is_available = False
        if member:
            try:
                turma = int(member.getProperty('turma'))
                return True
            except:
                return False
        else:        
            return False 
    
    def turma(self):
        member = self._get_member()
        if member:
            return member.getProperty('turma')
        return -1
    
    def dias(self):
        member = self._get_member()
        if member:
            data_formatura = datetime(2000+int(member.getProperty('turma')),12,15)
            data_formatura += timedelta(-data_formatura.weekday()+6)
            return (data_formatura-datetime.now()).days
        return -1
            
class AddForm(base.NullAddForm):

    def create(self):
        return Assignment()